package a;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @description:
 * @author: jinzewang
 * @project_name: farmpost
 * @date: 2022/12/16 14:58
 */
@Slf4j
public class SFTPJSCHUtils {

    /**
     * sftp下载远程文件
     * @param remoteServerIp
     * @param username
     * @param password
     * @param remoteFilePath
     * @param localFilePath
     */
    public static void downloadFileBySftp(String remoteServerIp, String username, String password, String remoteFilePath, String localFilePath) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(username, remoteServerIp, 22);
        } catch (JSchException e) {
            log.error("SFTPJSCHUtils downLoadFileBySftp jsch getSession error...msg is [{}]", e.toString());
        }
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        try {
            session.connect();
        } catch (JSchException e) {
            log.error("SFTPJSCHUtils downLoadFileBySftp session connect error...msg is [{}]", e.toString());
        }
        Channel channel = null;
        try {
            channel = session.openChannel("sftp");
        } catch (JSchException e) {
            log.error("SFTPJSCHUtils downLoadFileBySftp session openChannel error...msg is [{}]", e.toString());
        }
        try {
            channel.connect();
        } catch (JSchException e) {
            log.error("SFTPJSCHUtils downLoadFileBySftp channel connect error...msg is [{}]", e.toString());
        }
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        try {
            sftpChannel.get(remoteFilePath+"/test.txt", localFilePath);
        } catch (SftpException e) {
            log.error("SFTPJSCHUtils downLoadFileBySftp sftpChannel get error...msg is [{}]", e.toString());
        }
        sftpChannel.exit();
        session.disconnect();
    }

    @Deprecated
    public static void uploadFileBySftp(String remoteServerIp, String username, String password, String remoteFilePath, String localFilePath) {
        JSch jsch = new JSch();
        try {
            Session session = jsch.getSession(username, remoteServerIp, 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.put(remoteFilePath, localFilePath);
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException | SftpException e) {
            //To change body of catch statement use File | Settings | File Templates.
            log.error("SFTPJSCHUtils upLoadFileBySftp JschException error...msg is [{}]", e.toString());
        }
    }
}
